<template>
  <div class="address-edit-container">
    <el-card shadow="never" class="edit-card">
      <template #header>
        <div class="card-header">
          <span>编辑地址</span>
        </div>
      </template>

      <el-form 
        ref="formRef"
        :model="formData"
        :rules="rules"
        label-width="100px"
        label-position="right"
      >
        <el-form-item label="收货人" prop="receiver_name">
          <el-input
            v-model="formData.receiver_name"
            placeholder="请输入收货人姓名"
            clearable
          />
        </el-form-item>

        <el-form-item label="联系电话" prop="receiver_phone">
          <el-input
            v-model="formData.receiver_phone"
            placeholder="请输入联系电话"
            clearable
          />
        </el-form-item>

        <el-form-item label="详细地址" prop="address">
          <el-input
            v-model="formData.address"
            type="textarea"
            :rows="3"
            placeholder="请输入详细地址"
            clearable
          />
        </el-form-item>

        <el-form-item label="默认地址" prop="is_default">
          <el-switch
            v-model="formData.is_default"
            active-text="是"
            inactive-text="否"
          />
        </el-form-item>

        <el-form-item>
          <el-button
            type="primary"
            @click="submitForm"
            :loading="loading"
          >
            保存
          </el-button>
          <el-button @click="goBack">
            取消
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { updateAddress, getAddressList } from '../../api/address'

const route = useRoute()
const router = useRouter()
const loading = ref(false)
const formRef = ref(null)

// 表单数据
const formData = ref({
  id: '',
  receiver_name: '',
  receiver_phone: '',
  address: '',
  is_default: false
})

// 表单验证规则
const rules = {
  receiver_name: [
    { required: true, message: '请输入收货人姓名', trigger: 'blur' },
    { min: 2, max: 10, message: '长度在2到10个字符', trigger: 'blur' }
  ],
  receiver_phone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  address: [
    { required: true, message: '请输入详细地址', trigger: 'blur' },
    { min: 5, max: 100, message: '长度在5到100个字符', trigger: 'blur' }
  ]
}

// 获取地址详情
const fetchAddressDetail = async () => {
  try {
    loading.value = true
    const res = await getAddressList(route.params.id)
    if (res.status === 0) {
      formData.value = {
        id: res.data.id,
        receiver_name: res.data.receiver_name,
        receiver_phone: res.data.receiver_phone,
        address: res.data.address,
        is_default: res.data.is_default
      }
    } else {
      ElMessage.error(res.message || '获取地址详情失败')
      goBack()
    }
  } catch (error) {
    console.error('获取地址详情错误:', error)
    ElMessage.error('获取地址详情失败')
    goBack()
  } finally {
    loading.value = false
  }
}

// 提交表单
const submitForm = async () => {
  try {
    await formRef.value.validate()
    loading.value = true
    
    const res = await updateAddress(formData.value)
    if (res.status === 0) {
      ElMessage.success('地址更新成功')
      goBack()
    } else {
      ElMessage.error(res.message || '地址更新失败')
    }
  } catch (error) {
    console.error('更新地址错误:', error)
    if (error !== 'validate') {
      ElMessage.error('地址更新失败')
    }
  } finally {
    loading.value = false
  }
}

// 返回地址列表
const goBack = () => {
  router.push('/address')
}

onMounted(() => {
  if (route.params.id) {
    fetchAddressDetail()
  } else {
    ElMessage.error('地址ID不存在')
    goBack()
  }
})
</script>

<style scoped>
.address-edit-container {
  padding: 20px;
}

.edit-card {
  max-width: 800px;
  margin: 0 auto;
}

.card-header {
  font-size: 18px;
  font-weight: bold;
}
</style>